package com.bankcomm.audio;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;

import com.bankcomm.R;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.EMPView;
import com.bankcomm.util.BOCKeyMobile;
import com.rytong.tools.utils.LPToastUtil;

public class AudioServerManager {
	private AudioManager am;
	private int currentVolumeNum;
	private int currentNotiVolumeNum;
	private int currentRingVolumeNum;
	
	private static int CLOSE_DIALOG_TAG = 1001;
	private static int SHOW_DIALOG_TAG = 1002;
	private static int TOAST_ERROR_INFO = 1003;
	private static int SHOW_NOTIFICATIONS = 1004;
	private static int STREAM_VOLUME_MIN = 1005;
	private static int RESET_STREAM_VOLUME = 1006;
	
	private NotificationManager notificationManager;
	private Notification notifcation;
	
	private Context context;
	private BOCKeyMobile key;
	
	public Dialog mDialog;
	
	public BroadcastReceiver audioDeviceReceiver;
	private PhoneStateReceiver phoneStateReceiver;
	public static boolean isAudioAdapterConnect;
	
	public AudioServerManager(Context c, BOCKeyMobile key){
		this.context = c;
		this.key = key;
		isAudioAdapterConnect = true;
		createHandlerForAudioCard();
		registerAudioReceiver();
		registerPhoneStateReceiver();
		createProgressDialog();
	}
	
	/**
     * 注册监听耳机的广播接收器
     * 
     * **/
	public void registerAudioReceiver() {
		if (null == audioDeviceReceiver) {
			audioDeviceReceiver = new HeadsetPlugReceiver();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_HEADSET_PLUG);
		context.registerReceiver(audioDeviceReceiver, filter);
	}
	
	  /**
     * 注册监听来电状态的广播接收器
     * 
     * **/
	public void registerPhoneStateReceiver() {
		if (null == phoneStateReceiver) {
			phoneStateReceiver = new PhoneStateReceiver();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		context.registerReceiver(phoneStateReceiver, filter);
	}
	
	/**
	 * 创建handler处理监听音频卡
	 **/
	public void createHandlerForAudioCard() {
		EventHandler uhandler = new EventHandler();
		uhandler.eventHandler = new Handler() {
			public void handleMessage(Message msg) {
                //处理打开音频口交互管理器
				if (null != msg && msg.what == 1000) {
					setVolumeMax();
					if (key != null) {
						key.openDevice(key.signResult);
					}
				}
				//关闭加载框
				if (null != msg && msg.what == CLOSE_DIALOG_TAG) {
					if (mDialog.isShowing())
						mDialog.dismiss();
				}
				//显示加载框
				if (null != msg && msg.what == SHOW_DIALOG_TAG) {
					mDialog.show();
				}
				//模仿toast出现异常时提示
				if (null != msg && msg.what == TOAST_ERROR_INFO) {
					String errorInfo = (String) msg.obj;
					LPToastUtil.getInstance().getToast(errorInfo,
							context);

				}
				//显示出notification
				if (null != msg && msg.what == SHOW_NOTIFICATIONS) {
					showNotification(context.getString(R.string.tel_connect), context.getString(R.string.app_name), context.getString(R.string.tel_connect),
							R.string.app_name, R.drawable.icon);
				}
				
				// 所有声音设置静音
				if (null != msg && msg.what == STREAM_VOLUME_MIN) {
					setNotificationsAndRingVolumeMin();
					if (audioDeviceReceiver != null) {
						context.unregisterReceiver(audioDeviceReceiver);
					}
					if (phoneStateReceiver != null) {
						context.unregisterReceiver(phoneStateReceiver);
					}
				}
				
				//重新恢复声音大小
				if (null != msg && msg.what == RESET_STREAM_VOLUME) {
					if (audioDeviceReceiver != null) {
						context.unregisterReceiver(audioDeviceReceiver);
					}
					if (phoneStateReceiver != null) {
						context.unregisterReceiver(phoneStateReceiver);
					}
					reSetStreamVolume();
				}
			}
		};
	}
	
	// 将多媒体声音设置为最大、短信声和铃声为静音
	protected void setVolumeMax() {
		am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		currentNotiVolumeNum = am.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
		currentRingVolumeNum = am.getStreamVolume(AudioManager.STREAM_RING);
		currentVolumeNum = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);
		am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
		am.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
	}
	 /**
     * 设置多媒体声音、短信声和铃声为静音
     * **/
	protected void setNotificationsAndRingVolumeMin() {
		am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		currentNotiVolumeNum = am.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
		currentRingVolumeNum = am.getStreamVolume(AudioManager.STREAM_RING);
		currentVolumeNum = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
		am.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
	}
	
	/**
     * 重置声音
     * **/
	void reSetStreamVolume() {
		if (am != null) {
			am.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolumeNum, 0);
			am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, currentNotiVolumeNum, 0);
			am.setStreamVolume(AudioManager.STREAM_RING, currentRingVolumeNum, 0);
		}
	}
	
	 /**
     * 在状态栏显示notification
     * @param tickerText notification显示时的文字
     * @param  contentTitle 拉下状态栏显示的title
     * @param contentText 拉下状态栏显示的文字内容
     * **/
	private void showNotification(String tickerText, String contentTitle, String contentText, int id, int resId) {
		notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notifcation = new Notification(resId, tickerText, System.currentTimeMillis());

		// contentIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
		notifcation.flags = Notification.FLAG_AUTO_CANCEL;
		notifcation.setLatestEventInfo(context, contentTitle, contentText, null);
		notificationManager.notify(id, notifcation);

	}
	
	 /**
     * 创建加载弹出框
     * 
     * **/
	private void createProgressDialog() {
		mDialog=LPMid.getInstance().creatDialog(mDialog, context.getString(R.string.onMapLoading), (EMPView)context);
		mDialog.setCanceledOnTouchOutside(false);
	}
	
	public void closeDialog() {
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Message m = new Message();
					m.what = CLOSE_DIALOG_TAG;
					Handler handler = EventHandler.ut.eventHandler;
					Thread.sleep(500);
					handler.sendMessage(m);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	public void showDialog() {
		Message m = new Message();
		m.what = SHOW_DIALOG_TAG;
		Handler handler = EventHandler.ut.eventHandler;
		handler.sendMessage(m);
	}

	public static void sendError(String error) {
		Message m = new Message();
		m.what = TOAST_ERROR_INFO;
		m.obj = error;
		Handler handler = EventHandler.ut.eventHandler;
		handler.sendMessage(m);
	}
}
